<?php

/**
 * Description of Application_Model_Json
 *
 * @author Jean Brito
 */
abstract class Application_Model_Json extends Application_Model_Fix {

	const DIR='data/json';
	const EXTENSAO='.json';

	static public function index($model, $filter = null, $start = null, $limit = null, $sort = null) {
		self::read($model);
		return parent::index($model, $filter, $start, $limit, $sort);
	}

	static public function post($model,$params) {
		self::read($model);
		$result=parent::post($model,$params);
		self::write($model);
		return $result;
	}

	static public function delete($model,$id) {
		self::read($model);
		$result=parent::delete($model,$id);
		self::write($model);
		return $result;
	}

	static public function put($model,$id, $params) {
		self::read($model);
		$result=parent::put($model,$id,$params);
		self::write($model);
		return $result;
	}

	static public function read($model){
		$data=array();
		if(file_exists($model->getFileName())){
			$data=Zend_Json::decode(file_get_contents($model->getFileName()));
		}
		$model->setData($data);
		return $data;
	}

	static public function write($model){

		$fd=explode('/',trim($model->getFileName(),"/"));
		$file="./";
		foreach($fd as $d=>$dir){
			$file.=$dir;
			if(!is_dir($file)&&$d<(count($fd)-1)){
				mkdir($file);
			}
			$file.="/";
		}
		$fo=fopen($model->getFileName(),'w');
		fwrite($fo,Zend_Json::prettyPrint(Zend_Json::encode($model->getData()), array("indent" => "    ")));
		fclose($fo);
	}


}
